#include <iostream>
#include <functional>
#include <cstring>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <pthread.h>
#include "log.hpp"
#include "protocol.hpp"
using namespace std;
enum
{
    OK = 0,
    SOCKET_ERR,
    BIND_ERR,
    LISTEN_ERR,
    READ_ERR
};

class Server
{
    typedef function<void(Request &, Response &)> func_t;

public:
    Server(const uint16_t &port) : _fd(-1), _port(port) {}
    void init()
    {
        _fd = socket(AF_INET, SOCK_STREAM, 0);
        if (_fd == -1)
        {
            cerr << strerror(errno) << endl;
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL, "socket success");
        struct sockaddr_in addr;
        bzero(&addr, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_port = htons(_port);
        int n = bind(_fd, (struct sockaddr *)&addr, sizeof(addr));
        if (n == -1)
        {
            logMessage(ERROR, strerror(errno));
            exit(BIND_ERR);
        }
        logMessage(NORMAL, "bind success");

        n = listen(_fd, 5);
        if (n < 0)
        {
            cerr << strerror(errno) << endl;
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL, "listen success");
    }
    void handlerEntery(const int &fd, func_t func)
    {
        string inbuffer;
        while (1)
        {
            // 收到Req
            Request req;
            string req_str, req_text;
            if (recvPackage(fd, inbuffer, req_str) == false)
                return;
            // 去报头
            cout << "接收数据：" << req_str << endl;
            bool ret = deLength(req_str, req_text);
            if (ret == false)
                logMessage(ERROR, "Server : deLength fail");
            cout << "接收数据正文：" << req_text << endl;
            // 反序列化
            ret = req.deserialize(req_text);
            if (ret == false)
                logMessage(ERROR, "Server : deserialize fail");
            // 计算
            Response resp;
            func(req, resp);
            // 序列化
            string resp_text;
            ret = resp.serialize(resp_text);
            if (ret == false)
                logMessage(ERROR, "Server : deserialize fail");
            cout << "发送数据：" << resp_text << endl;
            // 加报头
            ret = enLength(resp_text);
            if (ret == false)
                logMessage(ERROR, "Server : enLength fail");
            cout << "发送数据正文：" << resp_text << endl;
            // 发送Resp
            send(fd, resp_text.c_str(), resp_text.size(), 0);
        }
    }
    // 进程版
    void start(func_t func)
    {
        signal(SIGCHLD, SIG_IGN);
        while (1)
        {
            struct sockaddr_in addr;
            socklen_t len = sizeof(addr);
            int socket = accept(_fd, (struct sockaddr *)&addr, &len);
            cout << "accept successs : " << socket << endl;
            if (socket == -1)
            {
                cerr << strerror(errno) << endl;
                continue;
            }
            pid_t id = fork();
            if (id == 0)
            {
                close(_fd);
                // serviceIO(socket);
                handlerEntery(socket, func);
                close(socket);
                exit(OK);
            }
            close(socket);
        }
    }
    void serviceIO(const int &fd)
    {
        while (1)
        {
            char buffer[1024];
            ssize_t size = read(fd, buffer, sizeof(buffer) - 1);
            if (size > 0)
            {
                buffer[size] = 0;
                cout << "[Client] : " << buffer << endl;
                string messages = buffer;
                ssize_t ret = write(fd, messages.c_str(), messages.size());
                if (ret < 0)
                {
                    cerr << strerror(errno) << endl;
                }
            }
            else if (size == 0)
            {
                cerr << "Client quit" << endl;
                break;
            }
            else
            {
                cerr << strerror(errno) << endl;
                exit(READ_ERR);
            }
        }
    }

    ~Server()
    {
        close(_fd);
    }

private:
    int _fd;
    uint16_t _port;
};